import logging
from dataclasses import dataclass

from src.application.order.enums import AuthorizationType
from src.application.order.uow import OrderUoW
from src.application.proxy.converters import convert_proxy_entity_to_dto
from src.application.user import dto
from src.application.user.converters import convert_active_user_entity_to_dto
from src.infrastructure.utils.helpers import get_server_proxies

logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class ChangeAuthorizationType:
    order_id: int
    authorization_type: AuthorizationType


class ChangeAuthorizationTypeHandler:
    """
    Создание заказа
    """

    def __init__(
        self,
        *,
        uow: OrderUoW,
    ) -> None:
        self._uow = uow

    async def __call__(self, command: ChangeAuthorizationType) -> dto.UserDTO:
        order = await self._uow.order_repo.acquire_order_by_id(order_id=command.order_id)
        order_proxies = [convert_proxy_entity_to_dto(proxy) for proxy in order.proxies]

        server_proxies = await get_server_proxies(order_proxies)  # TODO Подумать над этим

        try:
            await self._uow.order_repo.create_order(order)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()

        logger.info("Order created", extra={"order": order})

        order_dto = convert_active_user_entity_to_dto(order)

        return order_dto
